import { Form, Input, Button, Select, Space, message } from "antd";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useEffect } from "react";
import { v4 as uuidv4 } from "uuid";
import { CreateTask } from "./_graphql";

const { Option } = Select;

const layout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
const tailLayout = { wrapperCol: { offset: 6, span: 16 } };

const RemoveOutterApply = ({ record, reviewType }) => {
    const { remoteData } = useModel("global");
    const { baseInfo, memberInfo } = useModel("person.info");
    const { organizationUuid } = useModel("organization.info");
    const { applicationInfo, applicationUuid } = useModel("application.info");
    const { onCloseGlobalModal } = useModel("global.modal");
    const { members, reviewerRoles } = useModel("members.info");
    const { taskScene } = useModel("task.info");
    const [form] = Form.useForm();

    const state = useReactive({
        loading: false,
        taskRoles: [],
        roles: [],
        OutterMembers: [],
        omEouu: "",
        applyText: `【${baseInfo.realName}】把【${record.omName}】移除组织。`,
    });

    useEffect(() => {
        let taskRoles = taskScene["remove_organization_member"];
        if (Object.keys(taskRoles).find((key) => key === "charger")) {
            state.roles = Object.keys(taskRoles).filter((key) => key !== "charger");
            state.taskRoles = taskRoles;

            let arr = [];
            let obj = {};
            Object.keys(state.taskRoles).map((item) =>
                taskRoles[item].members?.map((_item) => {
                    if (taskRoles[item].isMany) {
                        arr.push(_item.omUuid);
                        obj[item] = arr;
                    } else {
                        obj[item] = _item.omUuid;
                    }
                })
            );
            form.setFieldsValue(obj);
        }
    }, [taskScene]);

    let onFinish = async (values) => {
        state.loading = true;
        let query = CreateTask;

        let graphql = ``;

        const taskInfo = {
            taUuid: uuidv4(),
            taName: "移除组织成员",
            taCrti: new Date().getUTCTime(),
            taStti: new Date().getUTCTime(),
            taType: "待办",
            aiUuid: applicationUuid,
            aiPath: "tasks",
            buUuid: record.omUuid,
            buType: "移除组织成员",
            buCons: record.omUuid,
            taCgud: baseInfo.uuid,
            taDesc: values.reason,
            taStat: "进行中",
            taLeve: 3,
            buTkey: "remove_organization_member/default",
            taTran: true,
        };

        state.roles.map((item, index) => {
            if (Array.isArray(values[item])) {
                values[item].map((_item, i) => {
                    graphql += `${"a" + index + i}:createTaskMember(
                        input: {taskMember: {taUuid: $taUuid, taRole: "${state.taskRoles[item].label}", omUuid: "${_item}", taRkey: "${item}"}}
                      ) {
                        clientMutationId
                      }`;
                });
            } else if (item !== "appUuid") {
                graphql += `${"c" + index}:createTaskMember(
                    input: {taskMember: {taUuid: $taUuid, taRole: "${state.taskRoles[item].label}", omUuid: "${values[item]}", taRkey: "${item}"}}
                  ) {
                    clientMutationId
                  }`;
            }
        });

        query = query.replace("#{graphql}", graphql);

        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/graphql/public_graphql_service",
            organizationUuid,
            params: { query, variables: taskInfo },
        });
        if (res) {
            message.success("成功提交移除成员任务");
            onCloseGlobalModal();
        }
        state.loading = false;
    };

    return (
        <Form {...layout} form={form} onFinish={onFinish}>
            <Form.Item label="申请内容">{state.applyText}</Form.Item>

            <Form.Item name="reason" label="申请原由">
                <Input />
            </Form.Item>

            {state?.roles?.map((key, index) => (
                <>
                    {state.taskRoles[key].isMany === true && (
                        <Form.Item label={state.taskRoles[key].label} name={key} key={index} rules={[{ required: true }]}>
                            <Select
                                mode="multiple"
                                showSearch
                                showArrow
                                optionFilterProp="label"
                                options={members}
                                fieldNames={{ label: "omName", value: "omUuid" }}
                                filterOption={(input, option) => option.omName.indexOf(input) != -1}
                            />
                        </Form.Item>
                    )}
                    {state.taskRoles[key].isMany === false && (
                        <Form.Item label={state.taskRoles[key].label} name={key} key={index} rules={[{ required: true }]}>
                            <Select
                                showSearch
                                showArrow
                                optionFilterProp="label"
                                options={members}
                                fieldNames={{ label: "omName", value: "omUuid" }}
                                filterOption={(input, option) => option.omName.indexOf(input) != -1}
                            />
                        </Form.Item>
                    )}
                </>
            ))}

            <Form.Item {...tailLayout}>
                <Space>
                    <Button type="primary" htmlType="submit">
                        提交任务
                    </Button>
                    <Button htmlType="button" onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    );
};

export default RemoveOutterApply;
